// 审计日志类型定义

// 审计日志记录类型
export interface AuditLog {
  id: string;
  timestamp: string;
  user: string;
  userId: string;
  action: string;
  module: string;
  details: string;
  ipAddress: string;
  status: 'success' | 'failed' | 'warning';
}

// 日志状态类型
export type LogStatus = 'success' | 'failed' | 'warning';

// 日志筛选条件类型
export interface LogFilters {
  searchQuery: string;
  status: string;
  module: string;
  action: string;
  dateRange: {
    start: string;
    end: string;
  };
  page: number;
  pageSize: number;
}

// 日志统计信息类型
export interface LogStatistics {
  totalLogs: number;
  successCount: number;
  failedCount: number;
  warningCount: number;
  topModules: Array<{ name: string; count: number }>;
  topActions: Array<{ name: string; count: number }>;
  dailyLogs: Array<{ date: string; count: number }>;
}

// 状态选项
export const statusOptions = [
  { value: 'all', label: '全部状态' },
  { value: 'success', label: '成功' },
  { value: 'failed', label: '失败' },
  { value: 'warning', label: '警告' },
];

// 模块选项
export const moduleOptions = [
  { value: 'all', label: '全部模块' },
  { value: 'system', label: '系统管理' },
  { value: 'user', label: '用户管理' },
  { value: 'student', label: '学生管理' },
  { value: 'teacher', label: '教师管理' },
  { value: 'class', label: '班级管理' },
  { value: 'attendance', label: '考勤管理' },
  { value: 'grades', label: '成绩管理' },
  { value: 'settings', label: '系统设置' },
  { value: 'audit', label: '审计日志' },
];

// 操作类型选项
export const actionOptions = [
  { value: 'all', label: '全部操作' },
  { value: 'login', label: '登录' },
  { value: 'logout', label: '登出' },
  { value: 'create', label: '创建' },
  { value: 'update', label: '更新' },
  { value: 'delete', label: '删除' },
  { value: 'view', label: '查看' },
  { value: 'import', label: '导入' },
  { value: 'export', label: '导出' },
  { value: 'settings', label: '设置' },
  { value: 'approve', label: '审批' },
  { value: 'reject', label: '拒绝' },
  { value: 'reset', label: '重置' },
];

// 分页大小选项
export const pageSizeOptions = [
  { value: 10, label: '10条/页' },
  { value: 20, label: '20条/页' },
  { value: 50, label: '50条/页' },
  { value: 100, label: '100条/页' },
];

// 日期范围选项（快捷筛选）
export const dateRangePresets = [
  { label: '今天', value: 'today' },
  { label: '昨天', value: 'yesterday' },
  { label: '最近7天', value: 'last7days' },
  { label: '最近30天', value: 'last30days' },
  { label: '本月', value: 'thisMonth' },
  { label: '上月', value: 'lastMonth' },
  { label: '自定义', value: 'custom' },
];

// 获取模块中文名
export const getModuleName = (module: string): string => {
  const moduleMap: { [key: string]: string } = {
    system: '系统',
    user: '用户',
    student: '学生',
    teacher: '教师',
    class: '班级',
    attendance: '考勤',
    grades: '成绩',
    settings: '设置',
    audit: '审计',
  };
  return moduleMap[module] || module;
};

// 获取操作中文名
export const getActionName = (action: string): string => {
  const actionMap: { [key: string]: string } = {
    login: '登录',
    logout: '登出',
    create: '创建',
    update: '更新',
    delete: '删除',
    view: '查看',
    import: '导入',
    export: '导出',
    settings: '设置',
    approve: '审批',
    reject: '拒绝',
    reset: '重置',
  };
  return actionMap[action] || action;
};

// 获取状态中文名
export const getStatusName = (status: LogStatus): string => {
  const statusMap: { [key in LogStatus]: string } = {
    success: '成功',
    failed: '失败',
    warning: '警告',
  };
  return statusMap[status] || status;
};

// 获取状态样式类
export const getStatusClass = (status: LogStatus): string => {
  const statusMap: { [key in LogStatus]: string } = {
    success: 'status-success',
    failed: 'status-failed',
    warning: 'status-warning',
  };
  return statusMap[status] || '';
};

// 生成默认筛选条件
export const getDefaultFilters = (): LogFilters => ({
  searchQuery: '',
  status: 'all',
  module: 'all',
  action: 'all',
  dateRange: {
    start: '',
    end: '',
  },
  page: 1,
  pageSize: 20,
});

// 根据预设获取日期范围
export const getDateRangeByPreset = (preset: string): { start: string; end: string } => {
  const today = new Date();
  const start = new Date();
  const end = new Date();
  
  switch (preset) {
    case 'today':
      start.setHours(0, 0, 0, 0);
      end.setHours(23, 59, 59, 999);
      break;
    case 'yesterday':
      start.setDate(today.getDate() - 1);
      start.setHours(0, 0, 0, 0);
      end.setDate(today.getDate() - 1);
      end.setHours(23, 59, 59, 999);
      break;
    case 'last7days':
      start.setDate(today.getDate() - 7);
      start.setHours(0, 0, 0, 0);
      end.setHours(23, 59, 59, 999);
      break;
    case 'last30days':
      start.setDate(today.getDate() - 30);
      start.setHours(0, 0, 0, 0);
      end.setHours(23, 59, 59, 999);
      break;
    case 'thisMonth':
      start.setDate(1);
      start.setHours(0, 0, 0, 0);
      end.setDate(1);
      end.setMonth(end.getMonth() + 1);
      end.setDate(0);
      end.setHours(23, 59, 59, 999);
      break;
    case 'lastMonth':
      start.setDate(1);
      start.setMonth(start.getMonth() - 1);
      start.setHours(0, 0, 0, 0);
      end.setDate(1);
      end.setHours(0, 0, 0, 0);
      end.setDate(0);
      end.setHours(23, 59, 59, 999);
      break;
    default:
      return { start: '', end: '' };
  }
  
  return {
    start: start.toISOString().split('T')[0],
    end: end.toISOString().split('T')[0],
  };
};

// 生成模拟审计日志数据
export const generateMockAuditLogs = (count: number = 1500): AuditLog[] => {
  const logs: AuditLog[] = [];
  const actions = ['login', 'logout', 'create', 'update', 'delete', 'view', 'import', 'export', 'settings', 'approve', 'reject', 'reset'];
  const modules = ['system', 'user', 'student', 'teacher', 'class', 'attendance', 'grades', 'settings', 'audit'];
  const users = [
    { id: 'admin001', name: '管理员' },
    { id: 'teacher001', name: '张老师' },
    { id: 'teacher002', name: '李老师' },
    { id: 'admin002', name: '系统管理员' },
    { id: 'teacher003', name: '王老师' },
    { id: 'teacher004', name: '陈老师' },
    { id: 'teacher005', name: '刘老师' },
  ];
  const statuses: Array<LogStatus> = ['success', 'failed', 'warning'];
  const ipRanges = ['192.168.1.', '10.0.0.', '172.16.0.', '127.0.0.'];

  // 生成指定数量的模拟数据
  for (let i = 0; i < count; i++) {
    const date = new Date();
    // 随机生成最近30天内的时间
    date.setDate(date.getDate() - Math.floor(Math.random() * 30));
    date.setHours(Math.floor(Math.random() * 24));
    date.setMinutes(Math.floor(Math.random() * 60));
    date.setSeconds(Math.floor(Math.random() * 60));
    
    const action = actions[Math.floor(Math.random() * actions.length)];
    const module = modules[Math.floor(Math.random() * modules.length)];
    const user = users[Math.floor(Math.random() * users.length)];
    
    // 根据操作类型调整状态分布，登录操作有一定比例的失败
    let status: LogStatus;
    if (action === 'login') {
      status = Math.random() > 0.1 ? 'success' : 'failed';
    } else {
      status = Math.random() > 0.15 ? 'success' : 
               Math.random() > 0.5 ? 'warning' : 'failed';
    }
    
    const ipAddress = `${ipRanges[Math.floor(Math.random() * ipRanges.length)]}${Math.floor(Math.random() * 255)}`;
    
    // 根据操作类型和模块生成详细信息
    let details = '';
    const moduleName = getModuleName(module);
    const actionName = getActionName(action);
    
    switch (action) {
      case 'login':
        details = status === 'success' ? '用户登录成功' : 
                  Math.random() > 0.5 ? '登录失败：密码错误' : '登录失败：账户锁定';
        break;
      case 'logout':
        details = '用户主动登出系统';
        break;
      case 'create':
        details = `创建了新的${moduleName}记录`;
        break;
      case 'update':
        details = `更新了${moduleName}的信息`;
        break;
      case 'delete':
        details = `删除了${moduleName}的记录`;
        break;
      case 'view':
        details = `查看了${moduleName}的信息`;
        break;
      case 'import':
        details = `导入了${moduleName}数据`;
        break;
      case 'export':
        details = `导出了${moduleName}数据`;
        break;
      case 'settings':
        details = `修改了${moduleName}相关设置`;
        break;
      case 'approve':
        details = `审批通过了${moduleName}的申请`;
        break;
      case 'reject':
        details = `拒绝了${moduleName}的申请`;
        break;
      case 'reset':
        details = `重置了${moduleName}的相关信息`;
        break;
      default:
        details = `${actionName}了${moduleName}`;
    }
    
    logs.push({
      id: `log-${Date.now()}-${i}`,
      timestamp: date.toISOString(),
      user: user.name,
      userId: user.id,
      action,
      module,
      details,
      ipAddress,
      status,
    });
  }
  
  // 按时间倒序排序
  return logs.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime());
};

// 计算日志统计信息
export const calculateLogStatistics = (logs: AuditLog[]): LogStatistics => {
  const successCount = logs.filter(log => log.status === 'success').length;
  const failedCount = logs.filter(log => log.status === 'failed').length;
  const warningCount = logs.filter(log => log.status === 'warning').length;
  
  // 统计模块使用频率
  const moduleCounts: { [key: string]: number } = {};
  logs.forEach(log => {
    moduleCounts[log.module] = (moduleCounts[log.module] || 0) + 1;
  });
  const topModules = Object.entries(moduleCounts)
    .sort(([, a], [, b]) => b - a)
    .slice(0, 5)
    .map(([name, count]) => ({ name: getModuleName(name), count }));
  
  // 统计操作使用频率
  const actionCounts: { [key: string]: number } = {};
  logs.forEach(log => {
    actionCounts[log.action] = (actionCounts[log.action] || 0) + 1;
  });
  const topActions = Object.entries(actionCounts)
    .sort(([, a], [, b]) => b - a)
    .slice(0, 5)
    .map(([name, count]) => ({ name: getActionName(name), count }));
  
  // 统计每日日志数量（最近7天）
  const dailyCounts: { [key: string]: number } = {};
  const today = new Date();
  
  // 初始化最近7天的日期
  for (let i = 6; i >= 0; i--) {
    const date = new Date(today);
    date.setDate(date.getDate() - i);
    const dateStr = date.toISOString().split('T')[0];
    dailyCounts[dateStr] = 0;
  }
  
  // 统计每日日志数
  logs.forEach(log => {
    const dateStr = log.timestamp.split('T')[0];
    if (dailyCounts[dateStr] !== undefined) {
      dailyCounts[dateStr]++;
    }
  });
  
  const dailyLogs = Object.entries(dailyCounts)
    .sort(([a], [b]) => a.localeCompare(b))
    .map(([date, count]) => ({ date, count }));
  
  return {
    totalLogs: logs.length,
    successCount,
    failedCount,
    warningCount,
    topModules,
    topActions,
    dailyLogs,
  };
};